home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-gobject / gtk-2.0 / glib / option.py < prev   
Encoding:
Python Source  |  2009-06-15  |  12.7 KB  |  351 lines

  1. # -*- Mode: Python -*-
  2. # pygobject - Python bindings for the GObject library
  3. # Copyright (C) 2006  Johannes Hoelzl
  4. #
  5. #   glib/option.py: GOption command line parser
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, write to the Free Software
  19. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  20. # USA
  21.  
  22. """GOption command line parser
  23.  
  24. Extends optparse to use the GOptionGroup, GOptionEntry and GOptionContext
  25. objects. So it is possible to use the gtk, gnome_program and gstreamer command
  26. line groups and contexts.
  27.  
  28. Use this interface instead of the raw wrappers of GOptionContext and
  29. GOptionGroup in glib.
  30. """
  31.  
  32. import sys
  33. import optparse
  34. from optparse import OptParseError, OptionError, OptionValueError, \
  35.                      BadOptionError, OptionConflictError
  36.  
  37. import glib
  38. _glib = sys.modules['glib._glib']
  39.  
  40. __all__ = [
  41.     "OptParseError",
  42.     "OptionError",
  43.     "OptionValueError",
  44.     "BadOptionError",
  45.     "OptionConflictError"
  46.     "Option",
  47.     "OptionGroup",
  48.     "OptionParser",
  49.     "make_option",
  50. ]
  51.  
  52. class Option(optparse.Option):
  53.     """Represents a command line option
  54.  
  55.     To use the extended possibilities of the GOption API Option
  56.     (and make_option) are extended with new types and attributes.
  57.  
  58.     Types:
  59.         filename   The supplied arguments are read as filename, GOption
  60.                    parses this type in with the GLib filename encoding.
  61.  
  62.     Attributes:
  63.         optional_arg  This does not need a arguement, but it can be supplied.
  64.         hidden        The help list does not show this option
  65.         in_main       This option apears in the main group, this should only
  66.                       be used for backwards compatibility.
  67.  
  68.     Use Option.REMAINING as option name to get all positional arguments.
  69.  
  70.     NOTE: Every argument to an option is passed as utf-8 coded string, the only
  71.           exception are options which use the 'filename' type, its arguments
  72.           are passed as strings in the GLib filename encoding.
  73.  
  74.     For further help, see optparse.Option.
  75.     """
  76.     TYPES = optparse.Option.TYPES + (
  77.         'filename',
  78.     )
  79.  
  80.     ATTRS = optparse.Option.ATTRS + [
  81.         'hidden',
  82.         'in_main',
  83.         'optional_arg',
  84.     ]
  85.  
  86.     REMAINING = '--' + _glib.OPTION_REMAINING
  87.  
  88.     def __init__(self, *args, **kwargs):
  89.         optparse.Option.__init__(self, *args, **kwargs)
  90.         if not self._long_opts:
  91.             raise ValueError("%s at least one long option name.")
  92.  
  93.         if len(self._long_opts) < len(self._short_opts):
  94.             raise ValueError(
  95.                 "%s at least more long option names than short option names.")
  96.  
  97.         if not self.help:
  98.             raise ValueError("%s needs a help message.", self._long_opts[0])
  99.  
  100.  
  101.     def _set_opt_string(self, opts):
  102.         if self.REMAINING in opts:
  103.             self._long_opts.append(self.REMAINING)
  104.         optparse.Option._set_opt_string(self, opts)
  105.         if len(self._short_opts) > len(self._long_opts):
  106.             raise OptionError("goption.Option needs more long option names "
  107.                               "than short option names")
  108.  
  109.     def _to_goptionentries(self):
  110.         flags = 0
  111.  
  112.         if self.hidden:
  113.             self.flags |= _glib.OPTION_FLAG_HIDDEN
  114.  
  115.         if self.in_main:
  116.             self.flags |= _glib.OPTION_FLAG_IN_MAIN
  117.  
  118.         if self.takes_value():
  119.             if self.optional_arg:
  120.                 flags |= _glib.OPTION_FLAG_OPTIONAL_ARG
  121.         else:
  122.             flags |= _glib.OPTION_FLAG_NO_ARG
  123.  
  124.         if self.type == 'filename':
  125.             flags |= _glib.OPTION_FLAG_FILENAME
  126.  
  127.         for (long_name, short_name) in zip(self._long_opts, self._short_opts):
  128.             yield (long_name[2:], short_name[1], flags, self.help, self.metavar)
  129.  
  130.         for long_name in self._long_opts[len(self._short_opts):]:
  131.             yield (long_name[2:], '\0', flags, self.help, self.metavar)
  132.  
  133. class OptionGroup(optparse.OptionGroup):
  134.     """A group of command line options.
  135.  
  136.     Arguements:
  137.        name:             The groups name, used to create the
  138.                          --help-{name} option
  139.        description:      Shown as title of the groups help view
  140.        help_description: Shown as help to the --help-{name} option
  141.        option_list:      The options used in this group, must be option.Option()
  142.        defaults:         A dicitionary of default values
  143.        translation_domain: Sets the translation domain for gettext().
  144.  
  145.     NOTE: This OptionGroup does not exactly map the optparse.OptionGroup
  146.           interface. There is no parser object to supply, but it is possible
  147.           to set default values and option_lists. Also the default values and
  148.           values are not shared with the OptionParser.
  149.  
  150.     To pass a OptionGroup into a function which expects a GOptionGroup (e.g.
  151.     gnome_program_init() ). OptionGroup.get_option_group() can be used.
  152.  
  153.     For further help, see optparse.OptionGroup.
  154.     """
  155.     def __init__(self, name, description, help_description="",
  156.                  option_list=None, defaults=None,
  157.                  translation_domain=None):
  158.         optparse.OptionContainer.__init__(self, Option, 'error', description)
  159.         self.name = name
  160.         self.parser = None
  161.         self.help_description = help_description
  162.         if defaults:
  163.             self.defaults = defaults
  164.  
  165.         self.values = None
  166.  
  167.         self.translation_domain = translation_domain
  168.  
  169.         if option_list:
  170.             for option in option_list:
  171.                 self.add_option(option)
  172.  
  173.     def _create_option_list(self):
  174.         self.option_list = []
  175.         self._create_option_mappings()
  176.  
  177.     def _to_goptiongroup(self, parser):
  178.         def callback(option_name, option_value, group):
  179.             if option_name.startswith('--'):
  180.                 opt = self._long_opt[option_name]
  181.             else:
  182.                 opt = self._short_opt[option_name]
  183.  
  184.             try:
  185.                 opt.process(option_name, option_value, self.values, parser)
  186.             except OptionValueError:
  187.                 error = sys.exc_info()[1]
  188.                 gerror = _glib.GError(str(error))
  189.                 gerror.domain = _glib.OPTION_ERROR
  190.                 gerror.code = _glib.OPTION_ERROR_BAD_VALUE
  191.                 gerror.message = str(error)
  192.                 raise gerror
  193.  
  194.         group = _glib.OptionGroup(self.name, self.description,
  195.                                     self.help_description, callback)
  196.         if self.translation_domain:
  197.             group.set_translation_domain(self.translation_domain)
  198.  
  199.         entries = []
  200.         for option in self.option_list:
  201.             entries.extend(option._to_goptionentries())
  202.         group.add_entries(entries)
  203.  
  204.         return group
  205.  
  206.     def get_option_group(self, parser = None):
  207.         """ Returns the corresponding GOptionGroup object.
  208.  
  209.         Can be used as parameter for gnome_program_init(), gtk_init().
  210.         """
  211.         self.set_values_to_defaults()
  212.         return self._to_goptiongroup(parser)
  213.  
  214.     def set_values_to_defaults(self):
  215.         for option in self.option_list:
  216.             default = self.defaults.get(option.dest)
  217.             if isinstance(default, basestring):
  218.                 opt_str = option.get_opt_string()
  219.                 self.defaults[option.dest] = option.check_value(
  220.                     opt_str, default)
  221.         self.values = optparse.Values(self.defaults)
  222.  
  223. class OptionParser(optparse.OptionParser):
  224.     """Command line parser with GOption support.
  225.  
  226.     NOTE: The OptionParser interface is not the exactly the same as the
  227.           optparse.OptionParser interface. Especially the usage parameter
  228.           is only used to show the metavar of the arguements.
  229.  
  230.     Attribues:
  231.         help_enabled:           The --help, --help-all and --help-{group}
  232.                                 options are enabled (default).
  233.         ignore_unknown_options: Do not throw a exception when a option is not
  234.                                 knwon, the option will be in the result list.
  235.  
  236.     OptionParser.add_option_group() does not only accept OptionGroup instances
  237.     but also glib.OptionGroup, which is returned by gtk_get_option_group().
  238.  
  239.     Only glib.option.OptionGroup and glib.option.Option instances should
  240.     be passed as groups and options.
  241.  
  242.     For further help, see optparse.OptionParser.
  243.     """
  244.  
  245.     def __init__(self, *args, **kwargs):
  246.         if 'option_class' not in kwargs:
  247.             kwargs['option_class'] = Option
  248.         self.help_enabled = kwargs.pop('help_enabled', True)
  249.         self.ignore_unknown_options = kwargs.pop('ignore_unknown_options',
  250.                                                  False)
  251.         optparse.OptionParser.__init__(self, add_help_option=False,
  252.                                        *args, **kwargs)
  253.  
  254.     def set_usage(self, usage):
  255.         if usage is None:
  256.             self.usage = ''
  257.         elif usage.startswith("%prog"):
  258.             self.usage = usage[len("%prog"):]
  259.         else:
  260.             self.usage = usage
  261.  
  262.     def _to_goptioncontext(self, values):
  263.         if self.description:
  264.             parameter_string = self.usage + " - " + self.description
  265.         else:
  266.             parameter_string = self.usage
  267.         context = _glib.OptionContext(parameter_string)
  268.         context.set_help_enabled(self.help_enabled)
  269.         context.set_ignore_unknown_options(self.ignore_unknown_options)
  270.  
  271.         for option_group in self.option_groups:
  272.             if isinstance(option_group, _glib.OptionGroup):
  273.                 g_group = option_group
  274.             else:
  275.                 g_group = option_group.get_option_group(self)
  276.             context.add_group(g_group)
  277.  
  278.         def callback(option_name, option_value, group):
  279.             if option_name.startswith('--'):
  280.                 opt = self._long_opt[option_name]
  281.             else:
  282.                 opt = self._short_opt[option_name]
  283.             opt.process(option_name, option_value, values, self)
  284.  
  285.         main_group = _glib.OptionGroup(None, None, None, callback)
  286.         main_entries = []
  287.         for option in self.option_list:
  288.             main_entries.extend(option._to_goptionentries())
  289.         main_group.add_entries(main_entries)
  290.         context.set_main_group(main_group)
  291.  
  292.         return context
  293.  
  294.     def add_option_group(self, *args, **kwargs):
  295.         if isinstance(args[0], basestring):
  296.             optparse.OptionParser.add_option_group(self,
  297.                 OptionGroup(self, *args, **kwargs))
  298.             return
  299.         elif len(args) == 1 and not kwargs:
  300.             if isinstance(args[0], OptionGroup):
  301.                 if not args[0].parser:
  302.                     args[0].parser = self
  303.                 if args[0].parser is not self:
  304.                     raise ValueError("invalid OptionGroup (wrong parser)")
  305.             if isinstance(args[0], _glib.OptionGroup):
  306.                 self.option_groups.append(args[0])
  307.                 return
  308.         optparse.OptionParser.add_option_group(self, *args, **kwargs)
  309.  
  310.     def _get_all_options(self):
  311.         options = self.option_list[:]
  312.         for group in self.option_groups:
  313.             if isinstance(group, optparse.OptionGroup):
  314.                 options.extend(group.option_list)
  315.         return options
  316.  
  317.     def _process_args(self, largs, rargs, values):
  318.         context = self._to_goptioncontext(values)
  319.  
  320.         # _process_args() returns the remaining parameters in rargs.
  321.         # The prepended program name is used to all g_set_prgname()
  322.         # The program name is cut away so it doesn't appear in the result.
  323.         rargs[:] = context.parse([sys.argv[0]] + rargs)[1:]
  324.  
  325.     def parse_args(self, args=None, values=None):
  326.         old_args = args or []
  327.         try:
  328.             options, args = optparse.OptionParser.parse_args(
  329.                 self, args, values)
  330.         except _glib.GError:
  331.             error = sys.exc_info()[1]
  332.             if error.domain != _glib.OPTION_ERROR:
  333.                 raise
  334.             if error.code == _glib.OPTION_ERROR_BAD_VALUE:
  335.                 raise OptionValueError(error.message)
  336.             elif error.code == _glib.OPTION_ERROR_UNKNOWN_OPTION:
  337.                 raise BadOptionError(error.message)
  338.             elif error.code == _glib.OPTION_ERROR_FAILED:
  339.                 raise OptParseError(error.message)
  340.             else:
  341.                 raise
  342.  
  343.         for group in self.option_groups:
  344.             for key, value in group.values.__dict__.items():
  345.                 options.ensure_value(key, value)
  346.  
  347.         args = args[2:-len(old_args)]
  348.         return options, args
  349.  
  350. make_option = Option
  351.